<html>
<head>

<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
    
 // Load the Visualization API and the bar chart package.
google.load("visualization", "1", {packages:['imagechart']});
      
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(initializeData);

/**
 * Once visualization API is loaded, retrieve data and set callbacks to run once retrieved.
 */
function initializeData() {
  // Get all of the dorm data from the spreadsheet.
  var dormDataURL = 'https://spreadsheets.google.com/tq?key=0An9ynmXUoikYdF85ZmJlWkFtZmVIVFFvWWxnN0ItRHc&range=A2:E169&gid=5';
  var dormDataQuery = new google.visualization.Query(dormDataURL);
  // Set a callback to run when the dorm data has been retrieved.
  dormDataQuery.send(displayDormData);
}

      
/**
 * Once dorm data is retrieved, create and display the chart with tooltips.
 */
function displayDormData(response) {
  // Process errors, if any.
  if (response.isError()) {
    alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
    return;
  }
  // Get the dorm data table.
  var data = response.getDataTable();

  // Generate an img tag with a chart URL and an accompanying map element for displaying data. 
  var img = document.createElement('img');
  img.setAttribute('src', getChartUrl(data));
  img.setAttribute('usemap', '#tooltipMap', 0);
  img.setAttribute('usemap', '#tooltipMap', 0);
  // Remove the blue line around the image.
  img.style.border = '0';
  document.getElementById('img').appendChild(img);
  document.getElementById('img').appendChild(createMap(data));
}

/**
 * Returns the URL for generating the chart.
 * Temporarily use the google visualization call to do it to simplify creation of the data parameter.
 * This results in 'flicker' and an extra HTTP call. 
 * We can generate the data param manually later in order to fix this.
 * Note we need to create a view containing just the last three columns.
 */
function getChartUrl(data) {
  // Create a view with just the x,y,value columns
  var view = new google.visualization.DataView(data);
  view.setColumns([2,3,4]);
  
  var chart = new google.visualization.ImageChart(document.getElementById('chart_div'));
  chart.draw(view, getOptions());

  // Get the URL without URL encoding of commas, pipes, and colons, since they take up too many characters and we have a 2K limit
  return chart.getImageUrl().replace(/%2C/g, ',').replace(/%7C/g, '|').replace(/%3A/g, ':');
}

 
/**
 * Builds and returns the options array for the chart.
 */    
function getOptions() {
  // Set up the options 
  var options = {};
  // Scatter chart
  options.cht = 's';
  // Image size
  options.chs = '500x200';
  // X-axis (0) and Y-axis (1) labels
  options.chxl = '0:||12am|1|2|3|4|5|6|7|8|9|10|11|12pm|1|2|3|4|5|6|7|8|9|10|11||1:||Sun|Mon|Tue|Wed|Thr|Fri|Sat|';
  // Adjust the X & Y axis with -1 so that dots line up correctly.
  // The last two numbers indicate the scaling range. 
  // Supply the lowest and highest value in the dataset to get automatic dot scaling. 
  options.chds = '-1,24,-1,7,0,600';
  // Shape marker: o = circle, 333333 = black, 1 = data series, -1 = allpoints, 20 = max size in pts.
  options.chm = 'o,459E00,1,-1,20';
  options.enableEvents = true;
  return options;
}
 

/**
 * Creates and returns the image map element.
 */
function createMap(data) {
  var map = document.createElement('map');
  map.setAttribute('id', 'tooltipMap');
  map.setAttribute('name', 'tooltipMap');

  // Initial offset into the chart to get the map aligned with the (x,y) values.
  // (47, 158) is the position of the bottom left dot
  var yOffset = 158;   
  var xOffset = 47;    
  var columnWidth = 18.5;
  var rowHeight = 21.5;
  var mapRadius = 8;

  // The numbers corresponding to the columns parts in the data object.
  var hourColumn = 0;
  var dayColumn = 1;
  var xColumn = 2;
  var yColumn = 3
  var valueColumn = 4;

  // loop through all the data points.
  for (var i = 0; i < data.getNumberOfRows(); i++) {
    // Get the x and y values.
    var y = data.getFormattedValue(i, yColumn);
    var x = data.getFormattedValue(i, xColumn);
    var label = 
      data.getFormattedValue(i,dayColumn) + ' ' +
      data.getFormattedValue(i,hourColumn) + ': ' +
      data.getFormattedValue(i,valueColumn) + ' wH';

    var area = document.createElement('area');
    area.setAttribute('id', '' + i);
    area.setAttribute('shape', 'circle');
    var xCoord = (xOffset + (columnWidth * x));
    var yCoord = (yOffset - (rowHeight * y));
    area.setAttribute('coords', '' + xCoord + ',' + yCoord +',' + mapRadius);
    area.setAttribute('nohref', 'nohref');
    area.setAttribute('onmouseover', 'showTooltip(\'' + label + '\',' + xCoord + ',' + yCoord + ');');
    area.setAttribute('onmouseout', 'hideTooltip();');
    map.appendChild(area);
  }
  return map;
}

function showTooltip(label, xCoord, yCoord) {
  var tooltip = document.getElementById('tooltip');
  tooltip.style.left = (xCoord + 20) + 'px';
  tooltip.style.top = (yCoord + 20) + 'px';
  tooltip.style.width = 'auto'; 
  tooltip.style.height = 'auto'; 
  tooltip.style.position = 'absolute';
  tooltip.style.background = '#fff';
  tooltip.innerHTML = label;
  tooltip.style.visibility = 'visible';
}

function hideTooltip() {
  document.getElementById('tooltip').style.visibility='hidden';
}

</script>
</head>

<body>
  <div style="text-indent: 50px; font-weight: bold; color: #459E00">Hale Ilima: Energy Consumption during the last 7 days</div>
  <div id="tooltip"></div>
  <div id="img"></div>
  <div style="display: none" id="chart_div"></div>
</body>
</html>

